package com.toppitch.site.feed;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.toppitch.site.data.NYTNewsItem;

public class NYTNewsSaxHandler extends DefaultHandler {
	private List<NYTNewsItem> newsItems = new ArrayList<NYTNewsItem>();
	private StringBuilder buffer = new StringBuilder();
	private NYTNewsItem item = null;

	public List<NYTNewsItem> getNewsItems() {
		return newsItems;
	}

	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		// no op
		if ("item".equalsIgnoreCase(qName)) {
			item = new NYTNewsItem();
			newsItems.add(item);
		} else if (item == null) {
			return;
		}
	}

	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		// no op
		if ("item".equalsIgnoreCase(qName)) {
			item = null;
		} else if (item == null) {
			buffer.setLength(0);
			return;
		}
		if ("title".equalsIgnoreCase(qName)) {
			item.setTitle(buffer.toString().trim());
		} else if ("link".equalsIgnoreCase(qName)) {
			item.setLink(buffer.toString().trim());
		} else if ("pubDate".equalsIgnoreCase(qName)) {
			item.setPubDate(buffer.toString().trim());
		}else if ("dc:creator".equalsIgnoreCase(qName)) {
			item.setCreator(buffer.toString().trim());
		}else if("description".equalsIgnoreCase(qName)){
			item.setDescription(buffer.toString().trim());
		}

		buffer.setLength(0);
	}

	public void characters(char ch[], int start, int length)
			throws SAXException {
		buffer.append(ch, start, length);
	}
}
